// pages/profile/settings.js
const app = getApp()
Page({
  data: {
    version: '1.0.0',
    cacheSize: '0 KB',
    notification: {
      reservation: true,
      activity: true,
      system: true
    }
  },

  onLoad() {
    this.getCacheSize()
    this.loadNotificationSettings()
  },

  // 加载通知设置
  loadNotificationSettings() {
    const settings = wx.getStorageSync('notificationSettings') || {}
    this.setData({
      notification: {
        reservation: settings.reservation !== false,
        activity: settings.activity !== false,
        system: settings.system !== false
      }
    })
  },

  // 保存通知设置
  saveNotificationSettings() {
    wx.setStorageSync('notificationSettings', this.data.notification)
  },

  // 切换预约提醒
  toggleReservation(e) {
    const value = e.detail.value
    this.setData({
      'notification.reservation': value
    })
    this.saveNotificationSettings()
  },

  // 切换活动通知
  toggleActivity(e) {
    const value = e.detail.value
    this.setData({
      'notification.activity': value
    })
    this.saveNotificationSettings()
  },

  // 切换系统消息
  toggleSystem(e) {
    const value = e.detail.value
    this.setData({
      'notification.system': value
    })
    this.saveNotificationSettings()
  },

  // 获取缓存大小
  getCacheSize() {
    wx.getStorageInfo({
      success: (res) => {
        const size = res.currentSize
        this.setData({
          cacheSize: size > 1024 ? `${(size / 1024).toFixed(1)} MB` : `${size} KB`
        })
      }
    })
  },

  // 清除缓存
  clearCache() {
    wx.showModal({
      title: '提示',
      content: '确定要清除缓存吗？',
      success: (res) => {
        if (res.confirm) {
          wx.clearStorageSync()
          wx.showToast({
            title: '缓存已清除',
            icon: 'success'
          })
          this.getCacheSize()
        }
      }
    })
  },

  // 修改手机号
  updatePhone() {
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    })
  },

  // 修改密码
  updatePassword() {
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    })
  },

  // 隐私政策
  navigateToPrivacy() {
    wx.navigateTo({
      url: '/pages/profile/privacy'
    })
  },

  // 检查版本
  checkVersion() {
    wx.showToast({
      title: '当前已是最新版本',
      icon: 'success'
    })
  },

  // 关于校史馆
  navigateToAbout() {
    wx.navigateTo({
      url: '/pages/profile/about'
    })
  },

  // 退出登录
  logout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('token')
          wx.removeStorageSync('userInfo')
          // 退出登录则删除token
          app.globalData.token = '';
          wx.showToast({
            title: '已退出登录',
            icon: 'success',
            complete: () => {
              wx.reLaunch({
                url: '/pages/index/index'
              })
            }
          })
        }
      }
    })
  }
})